package lzy.controller;

import lzy.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;

import lzy.entity.FarmOperation;
import lzy.service.FarmOperationService;
import lzy.entity.EnvironmentData;
import lzy.entity.CropStatus;
import lzy.service.EnvironmentDataService;
import lzy.service.CropStatusService;
import lzy.service.PestDetectionService;
import lzy.entity.PestDetection;
import lzy.service.BaseService;
import lzy.entity.Base;
import lzy.entity.SowHarvest;
import lzy.service.SowHarvestService;

import java.util.Map;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
@RequestMapping("/production")
public class ProductionController {



    @Autowired
    private FarmOperationService farmOperationService;
    @Autowired
    private EnvironmentDataService environmentDataService;
    @Autowired
    private CropStatusService cropStatusService;
    @Autowired
    private PestDetectionService pestDetectionService;
    @Autowired
    private BaseService baseService;
    @Autowired
    private SowHarvestService sowHarvestService;

    /**
     * 生产首页仪表盘页面
     * 仅生产人员可访问，未登录或无权限会跳转到登录页
     */
    @GetMapping("/dashboard")
    public String productionDashboard(HttpSession session, RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            redirectAttributes.addFlashAttribute("error", "请先登录！");
            return "redirect:/login";
        }
        if (!"PRODUCING".equals(user.getRole())) {
            redirectAttributes.addFlashAttribute("error", "您没有权限访问此页面！");
            return "redirect:/login";
        }
        return "dashboard_pd";
    }

    /**
     * 农事操作管理页面
     * 仅生产人员可访问，未登录或无权限会跳转到登录页
     * 查询所有农事操作并传递到前端页面
     */
    @GetMapping("/farming_management")
    public String farmingManagement(
        @RequestParam(required = false) String mainType,
        @RequestParam(required = false) String baseId,
        @RequestParam(required = false) String startDate,
        @RequestParam(required = false) String endDate,
        HttpSession session, RedirectAttributes redirectAttributes, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            redirectAttributes.addFlashAttribute("error", "请先登录！");
            return "redirect:/login";
        }
        if (!"PRODUCING".equals(user.getRole())) {
            redirectAttributes.addFlashAttribute("error", "您没有权限访问此页面！");
            return "redirect:/login";
        }
        // 筛选农事操作
        java.util.List<FarmOperation> operations = farmOperationService.findByFilter(mainType, baseId, startDate, endDate);
        model.addAttribute("farmingOperations", operations);
        // 查询待处理病虫害
        java.util.List<PestDetection> pestDetectionList = pestDetectionService.getPendingPests();
        model.addAttribute("pestDetectionList", pestDetectionList);

        int weeklyCompleted = pestDetectionService.countReviewedIn7Days();
        int reviewed = pestDetectionService.countAllReviewed();
        int total = pestDetectionService.countAll();
        double completionRate = total > 0 ? (reviewed * 100.0 / total) : 0.0;
        model.addAttribute("weeklyCompleted", weeklyCompleted);
        model.addAttribute("completionRate", String.format("%.1f", completionRate));
        return "production/farming_management";
    }

    /**
     * 生产环境监控页面
     * 支持按基地ID和记录日期筛选环境数据
     * 若有筛选条件，计算筛选结果的温度、湿度、土壤湿度平均值并传递到前端
     * 还会传递所有可选基地ID、日期、筛选结果、最新一条环境数据等
     * 仅生产人员可访问，未登录或无权限会跳转到登录页
     */
    @GetMapping("/environment_monitor")
    public String environmentMonitor(@RequestParam(required = false) String baseId,
                                     @RequestParam(required = false) String recordDate,
                                     HttpSession session, RedirectAttributes redirectAttributes, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            redirectAttributes.addFlashAttribute("error", "请先登录！");
            return "redirect:/login";
        }
        if (!"PRODUCING".equals(user.getRole())) {
            redirectAttributes.addFlashAttribute("error", "您没有权限访问此页面！");
            return "redirect:/login";
        }

        if (baseId != null && baseId.isEmpty()) baseId = null;
        if (recordDate != null && recordDate.isEmpty()) recordDate = null;

        java.util.List<String> baseIdList = environmentDataService.findAllBaseIds();
        java.util.List<String> recordDateList = environmentDataService.findAllRecordDates();
        java.util.List<EnvironmentData> list = environmentDataService.findByFilter(baseId, recordDate);
        model.addAttribute("baseIdList", baseIdList);
        model.addAttribute("recordDateList", recordDateList);
        model.addAttribute("environmentRecords", list);
        
        EnvironmentData latest = environmentDataService.findLatest();
        model.addAttribute("latestEnv", latest);
        model.addAttribute("selectedBaseId", baseId);
        model.addAttribute("selectedRecordDate", recordDate);

        //-----------------------平均温度（定位好像出了一点问题）-----------------------------------
        Double avgTemp = null, avgAirHumidity = null, avgSoilHumidity = null;
        if ((baseId != null && !baseId.isEmpty()) || (recordDate != null && !recordDate.isEmpty())) {
            if (list != null && !list.isEmpty()) {
                avgTemp = list.stream().filter(e -> e.getTemperature() != null)
                        .mapToDouble(EnvironmentData::getTemperature).average().orElse(Double.NaN);
                avgAirHumidity = list.stream().filter(e -> e.getAirHumidity() != null)
                        .mapToDouble(EnvironmentData::getAirHumidity).average().orElse(Double.NaN);
                avgSoilHumidity = list.stream().filter(e -> e.getSoilHumidity() != null)
                        .mapToDouble(EnvironmentData::getSoilHumidity).average().orElse(Double.NaN);
            }
        }
        model.addAttribute("avgTemp", avgTemp);
        model.addAttribute("avgAirHumidity", avgAirHumidity);
        model.addAttribute("avgSoilHumidity", avgSoilHumidity);

        // -----------------------图表数据准备---------------------------------
        java.util.List<String> chartLabels = new java.util.ArrayList<>();
        java.util.List<Double> tempData = new java.util.ArrayList<>();
        java.util.List<Double> humidityData = new java.util.ArrayList<>();
        String chartType = "none";
        if ((baseId != null && !baseId.isEmpty()) && (recordDate == null || recordDate.isEmpty())) {
            // 只筛选了基地，按时间排序，折线图
            list.sort(java.util.Comparator.comparing(EnvironmentData::getRecordTime));
            for (EnvironmentData e : list) {
                chartLabels.add(e.getRecordTime());
                tempData.add(e.getTemperature());
                humidityData.add(e.getAirHumidity());
            }
            chartType = "line";
        } else if ((baseId == null || baseId.isEmpty()) && (recordDate != null && !recordDate.isEmpty())) {
            // 只筛选了日期，按基地分组，柱状图
            java.util.Map<String, java.util.List<EnvironmentData>> group = new java.util.HashMap<>();
            for (EnvironmentData e : list) {
                group.computeIfAbsent(e.getBaseId(), k -> new java.util.ArrayList<>()).add(e);
            }
            for (String id : group.keySet()) {
                chartLabels.add(id);
                java.util.List<EnvironmentData> groupList = group.get(id);
                tempData.add(groupList.stream().filter(e -> e.getTemperature() != null).mapToDouble(EnvironmentData::getTemperature).average().orElse(Double.NaN));
                humidityData.add(groupList.stream().filter(e -> e.getAirHumidity() != null).mapToDouble(EnvironmentData::getAirHumidity).average().orElse(Double.NaN));
            }
            chartType = "bar";
        } else {
            chartType = "none";
        }
        model.addAttribute("chartType", chartType);
        model.addAttribute("chartLabels", chartLabels);
        model.addAttribute("tempData", tempData);
        model.addAttribute("humidityData", humidityData);

        return "production/environment_monitor";
    }

    /**
     * 作物状态监控页面
     * 支持按基地ID筛选，显示茎粗和植株高度趋势图
     */
    @GetMapping("/crop_status")
    public String cropStatus(@RequestParam(required = false) String baseId,
                            HttpSession session, RedirectAttributes redirectAttributes, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            redirectAttributes.addFlashAttribute("error", "请先登录！");
            return "redirect:/login";
        }
        if (!"PRODUCING".equals(user.getRole())) {
            redirectAttributes.addFlashAttribute("error", "您没有权限访问此页面！");
            return "redirect:/login";
        }

        java.util.List<String> baseIdList = cropStatusService.findAllBaseIds();
        model.addAttribute("baseIdList", baseIdList);
        model.addAttribute("selectedBaseId", baseId);
        java.util.List<CropStatus> list;
        if (baseId != null && !baseId.isEmpty()) {
            list = cropStatusService.findByBaseId(baseId);
        } else {
            list = cropStatusService.findAll();
        }
        model.addAttribute("cropStatus", list);

        // 趋势图数据
        java.util.List<String> trendLabels = new java.util.ArrayList<>();
        java.util.List<Double> stemData = new java.util.ArrayList<>();
        java.util.List<Double> heightData = new java.util.ArrayList<>();
        if (baseId != null && !baseId.isEmpty() && list != null && !list.isEmpty()) {
            list = list.stream()
                .filter(c -> c.getDetectTime() != null && c.getStemThickness() != null && c.getHeight() != null)
                .sorted(java.util.Comparator.comparing(CropStatus::getDetectTime))
                .collect(java.util.stream.Collectors.toList());
            for (CropStatus c : list) {
                trendLabels.add(c.getDetectTime());
                stemData.add(c.getStemThickness());
                heightData.add(c.getHeight());
            }
        }
        model.addAttribute("trendLabels", trendLabels);
        model.addAttribute("stemData", stemData);
        model.addAttribute("heightData", heightData);
        // 传递JSON字符串
        try {
            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
            model.addAttribute("trendLabelsJson", objectMapper.writeValueAsString(trendLabels));
            model.addAttribute("stemDataJson", objectMapper.writeValueAsString(stemData));
            model.addAttribute("heightDataJson", objectMapper.writeValueAsString(heightData));
        } catch (Exception e) {
            model.addAttribute("trendLabelsJson", "[]");
            model.addAttribute("stemDataJson", "[]");
            model.addAttribute("heightDataJson", "[]");
        }
        return "production/crop_status";
    }

    /**
     * 种植大棚管理页面
     * 仅生产人员可访问，未登录或无权限会跳转到登录页
     * 查询所有基地并传递到前端页面
     */
    @GetMapping("/greenhouse_management")
    public String greenhouseManagement(HttpSession session, RedirectAttributes redirectAttributes, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            redirectAttributes.addFlashAttribute("error", "请先登录！");
            return "redirect:/login";
        }
        if (!"PRODUCING".equals(user.getRole())) {
            redirectAttributes.addFlashAttribute("error", "您没有权限访问此页面！");
            return "redirect:/login";
        }
        java.util.List<Base> baseList = baseService.findAll();
        model.addAttribute("baseList", baseList);
        return "production/greenhouse_management";
    }

    @PostMapping("/addGreenhouse")
    @ResponseBody
    public String addGreenhouse(@ModelAttribute lzy.entity.Base base) {
        baseService.addBase(base);
        return "success";
    }


    /**
     * 保存农事操作（AJAX接口）
     * 接收前端传来的农事操作，直接保存
     * 返回"success"字符串
     */
    @PostMapping("/saveFarmOperation")
    @ResponseBody
    public String saveFarmOperation(@RequestBody FarmOperation operation) {
        farmOperationService.save(operation);
        return "success";
    }

    @PostMapping("/updatePestStatus")
    @ResponseBody
    public String updatePestStatus(@RequestBody Map<String, Object> payload) {
        Object idObj = payload.get("detectId");
        Integer detectId = null;
        if (idObj instanceof Integer) {
            detectId = (Integer) idObj;
        } else if (idObj instanceof Number) {
            detectId = ((Number) idObj).intValue();
        } else if (idObj != null) {
            detectId = Integer.parseInt(idObj.toString());
        }
        String status = (String) payload.get("status");
        pestDetectionService.updateStatus(detectId, status);
        return "success";
    }

    @GetMapping("/sow_harvest_management")
    public String sowHarvestManagement(@RequestParam(required = false) String sowHarvestId,
                                       @RequestParam(required = false) Integer baseId,
                                       @RequestParam(required = false) String startSowTime,
                                       @RequestParam(required = false) String endSowTime,
                                       @RequestParam(required = false) String status,
                                       HttpSession session, RedirectAttributes redirectAttributes, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            redirectAttributes.addFlashAttribute("error", "请先登录！");
            return "redirect:/login";
        }
        if (!"PRODUCING".equals(user.getRole())) {
            redirectAttributes.addFlashAttribute("error", "您没有权限访问此页面！");
            return "redirect:/login";
        }
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
        java.util.Date start = null, end = null;
        try { if (startSowTime != null && !startSowTime.isEmpty()) start = sdf.parse(startSowTime); } catch (Exception ignored) {}
        try { if (endSowTime != null && !endSowTime.isEmpty()) end = sdf.parse(endSowTime); } catch (Exception ignored) {}
        java.util.List<SowHarvest> list = sowHarvestService.findByFilter(sowHarvestId, baseId, start, end, status);
        model.addAttribute("sowHarvestList", list);
        model.addAttribute("sowHarvestId", sowHarvestId);
        model.addAttribute("baseId", baseId);
        model.addAttribute("startSowTime", startSowTime);
        model.addAttribute("endSowTime", endSowTime);
        model.addAttribute("status", status);
        return "production/sow_harvest_management";
    }

    @PostMapping("/sow_harvest/add")
    @ResponseBody
    public String addSowHarvest(@RequestBody SowHarvest record) {
        sowHarvestService.add(record);
        return "success";
    }

    @PostMapping("/sow_harvest/update")
    @ResponseBody
    public String updateSowHarvest(@RequestBody SowHarvest record) {
        sowHarvestService.update(record);
        return "success";
    }

    @PostMapping("/sow_harvest/delete")
    @ResponseBody
    public String deleteSowHarvest(@RequestBody java.util.Map<String, String> payload) {
        String sowHarvestId = payload.get("sowHarvestId");
        sowHarvestService.delete(sowHarvestId);
        return "success";
    }
} 